import { defineStore } from "pinia";
import axios from "axios";
import { UserState } from "@/stores/interface";
import piniaPersistConfig from "@/config/piniaPersist";
import ACrypto from "@/utils/crypto";
import { USER_LIST } from "../mutation-types";

export const useUserStore = defineStore({
  id: "user",
  state: (): UserState => ({
    token: "",
    userInfo: {},
    userList: [],
    fileCount: 0
  }),
  getters: {
    getUserList(state) {
      if (Object.keys(state.userList).length === 0) {
        const newUserList = ACrypto.getSS(window.sessionStorage.getItem(USER_LIST) as string, USER_LIST);
        state.userList = newUserList || [];
      }
      return state.userList;
    }
  },
  actions: {
    // Set Token
    setToken(token: string) {
      this.token = token;
    },
    // Set setUserInfo
    setUserInfo(userInfo: UserState["userInfo"]) {
      this.userInfo = userInfo;
    },
    SetUserList(userList: any[]) {
      this.userList = userList;
      ACrypto.setSS(userList, USER_LIST);
    },
    setFileCount(count: number) {
      this.fileCount = count;
    },
    //DF的SSO验证ticket是否正确合法
    async ssoLogin(url: string) {
      const response = await axios.get(url);
      return response.data;
    }
  },
  persist: piniaPersistConfig("user", ["token", "userInfo", "userList"])
});
